﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutomationHost.ViewModels;
using System.Xml.Linq;

namespace AutomationHost.Areas.Result.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        string conn = System.Configuration.ConfigurationManager.ConnectionStrings["HisoftSmartEntities"].ConnectionString;
            
        public ActionResult Index()
        {
            using (HisoftSmartEntities db = new HisoftSmartEntities(conn))
            {
                ResultIndexPage model = new ResultIndexPage();
                model.Results = new List<TestCaseResult>();
                foreach (var testResult in db.TestCaseResults.OrderByDescending(r => r.ID).ToList())
                {
                    testResult.TestPlanID = testResult.TestRun.TestPlanID;
                    testResult.TestPlanName = testResult.TestRun.TestPlan.Name;

                    Device d = testResult.TestRun.Device;
                    testResult.Device = new Device()
                    {
                        GUID = d.GUID,
                        Name = d.Name,
                        OS = d.OS,
                        OSVersion = d.OSVersion,
                        IP = d.IP
                    };

                    model.Results.Add(testResult);
                }

                return View(model);
            }
        }

        public ActionResult Details(int id)
        {
            using (HisoftSmartEntities db = new HisoftSmartEntities(conn))
            {
                ResultDetailsPage model = new ResultDetailsPage();
                model.TestResult = db.TestCaseResults.First(r => r.ID == id);
                model.TestResult.ActionResultModels = new List<ActionResultModel>();
                XDocument xDoc = XDocument.Parse(model.TestResult.ActionResults);
                foreach (var testAction in xDoc.Descendants("TestAction"))
                {
                    int actionID = int.Parse(testAction.Attribute("ID").Value);
                    var action = db.Actions.First(a =>a.ID==actionID);
                    model.TestResult.ActionResultModels.Add(new ActionResultModel()
                    {
                        Description = action.Description,
                        Name = action.Name,
                        Params = testAction.Attribute("Params").Value,
                        Result = testAction.Attribute("Result").Value,
                        Return = action.Result,
                        ID = actionID
                    });
                }

                return View(model);
            }
        }
    }
}
